package com.itheima.Servlet;

import com.itheima.domain.Student;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Map;

@WebServlet("/stu/updateStudent")
public class updateStudent extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //1. 获取前端传过来的学生信息
        Map<String, String[]> map = req.getParameterMap();
        //1.1 封装新的学生信息
        Student newStu = new Student();
        try {
            //使用工具类进行封装
            BeanUtils.populate(newStu, map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //1.将文件中所有学生信息先读取出来,存入集合
        //1.1获取真实路径
        ServletContext context = getServletContext();
        String realPath = context.getRealPath("/stu.txt");
        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(realPath), "utf-8"));
        //2.创建集合对象，用于保存Student对象
        ArrayList<Student> list = new ArrayList<>();
        //3.循环读取文件中的数据，将数据封装到Student对象中。再把多个学生对象添加到集合中
        String io;
        while((io=br.readLine())!=null){
            Student stu = new Student();
            String[] split = io.split(",");

            stu.setSid(split[0]);
            stu.setUsername(split[1]);
            stu.setAge(Integer.parseInt(split[2]));
            stu.setScore(Integer.parseInt(split[3]));
            list.add(stu);
        }
        for (int i = 0; i < list.size(); i++) {
            //找到学号要修改的对应学生的索引位置
            Student stu = list.get(i);
            if(stu.getSid().equalsIgnoreCase(newStu.getSid())){
                //将该索引位置替换为新的学生对象
                list.set(i,newStu);
            }
        }
        //将集合中最新数据写出到文件,覆盖原有信息
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(realPath),"UTF-8"));
        for (Student student : list) {
            bw.write(student.toString());
            bw.newLine();
            bw.flush();
        }

        bw.close();
        //重定向到findAllStudent
        resp.sendRedirect(context.getContextPath()+"/stu/findAllStudent");

    }



    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
